import logging
import os
from time import strftime


def safe_mkdir(path):
    if not os.path.exists(path):
        os.makedirs(path)


def init_logger(name=__name__, output_folder=None, level=logging.DEBUG,
                log_file_name=strftime("%Y-%m-%d") + '.log'):
    """
    Initialize a standard logger.

    Args:
        name:
        output_folder:
        level:
        log_file_name:

    Returns:
        the logger.
    """

    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

    def get_console_handler(formatter):
        console = logging.StreamHandler()
        console.setLevel(logging.ERROR)
        console.setFormatter(formatter)
        return console

    def get_file_handler(path, formatter):
        file_handler = logging.FileHandler(path)
        file_handler.setLevel(level)
        file_handler.setFormatter(formatter)
        return file_handler

    logger = logging.getLogger(name)
    logger.addHandler(get_console_handler(formatter))

    if output_folder:
        safe_mkdir(output_folder)
        log_file_path = os.path.join(output_folder, log_file_name)
        logger.addHandler(get_file_handler(log_file_path, formatter))

    return logger